/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
/* eslint-disable react/jsx-no-bind */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Button, Form, Modal, message, Popconfirm } from 'antd';
import { cloneDeep, uniq } from 'lodash';
import question from '@/assets/question.svg';
import PhoneVerificationCode from '@/components/PhoneVerificationCode';
import { isLegalData } from '@/utils/utils';
import EdiTable from './ediTable';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import styles from './index.less';

@connect(({ loading, configuration, allocation, operator, global, user }) => ({
  configuration,
  hasAuthToChangeHtPwd: global.hasAuthToChangeHtPwd,
  expandedRowKeys: operator.expandedRowKeys,
  listPagination: operator.pagination,
  stoAccountInfo: allocation.stoAccountInfo,
  user_info: user.currentUser.user_info,
  loading: loading.effects['configuration/getConInfo'],
  getBranchInfo: loading.effects['configuration/getBranchInfo'],
}))
@Form.create()
class Configuration extends PureComponent {
  constructor(props) {
    super(props);
    const { getBranchInfo, hasAuthToChangeHtPwd } = this.props;
    this.expandBrand = hasAuthToChangeHtPwd ? ['yd', 'yt', 'ht'] : ['yd', 'yt', 'ems'];
    this.columnsTable = [
      {
        title: '快递品牌',
        dataIndex: 'brand',
        align: 'center',
        width: 100,
        render: (_, record) => {
          const { brand } = this.state;
          const { expandRender } = record;
          if (this.expandBrand.includes(record.brand) && expandRender) return null;
          return <span>{brand.map(item => item.brand == record.brand && item.name)}</span>;
        },
      },
      {
        title: '网点编号',
        dataIndex: 'branch_code',
        align: 'center',
        width: 160,
        selectable: true,
        getBranchInfo,
        rules: [
          {
            required: true,
            message: '请选择网点编号',
          },
        ],
      },
      {
        title: () => (
          <div>
            巴枪账号
            <img
              alt=""
              onClick={this.onQuestionClick}
              style={{ cursor: 'pointer', marginLeft: 5 }}
              src={question}
            />
          </div>
        ),
        dataIndex: 'gun_account',
        align: 'center',
        width: 220,
        editable: true,
        placeholder: '请输入巴枪账号',
        rules: [
          {
            code: 3001,
            required: true,
            pattern: /^[a-zA-Z0-9.]{3,15}$/,
            message: '请输入3到15位数字或字母可以包含字符（.）',
            tag: '巴枪账号',
          },
        ],
        render: (text, record) => {
          const { brand } = record;
          return brand === 'sto' ? text : null;
        },
      },
      {
        title: '巴枪密码',
        dataIndex: 'gun_pwd',
        align: 'center',
        width: 220,
        editable: true,
        placeholder: '请输入巴枪密码',
        rules: [
          {
            code: 3002,
            // eslint-disable-next-line no-useless-escape
            pattern: /^[0-9a-zA-Z`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{1,20}$/,
            message: '请输入1到20位数字或字母或者特殊符号',
            tag: '巴枪密码',
          },
        ],
      },
      {
        dataIndex: 'gun_account_v2',
        align: 'center',
        width: 220,
        editable: true,
        placeholder: '请输入如来神掌手机号',
        expandTabledRender: true,
        rules: [
          {
            code: 3001,
            required: false,
            pattern: /^1[2-9]{1}[0-9]{1}\d{8}$/,
            message: '请输正确的手机号',
            tag: '手机号',
          },
        ],
      },
      {
        dataIndex: 'gun_pwd_v2',
        align: 'center',
        width: 220,
        editable: true,
        placeholder: '请输入如来神掌密码',
        expandTabledRender: true,
        rules: [
          {
            code: 3001,
            required: false,
            // eslint-disable-next-line no-useless-escape
            pattern: /^[0-9a-zA-Z`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{1,20}$/,
            message: '请输入1到20位数字或字母或者特殊符号',
            tag: '手机密码',
          },
        ],
      },
      {
        title: '三段码',
        dataIndex: 'third_code',
        align: 'center',
        width: 220,
        editable: true,
        placeholder: '请输入三段码',
        rules: [
          {
            code: 3003,
            // eslint-disable-next-line no-useless-escape
            pattern: /^[0-9a-zA-Z`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{1,15}$/,
            message: '请输入1到15位数字或字母或者特殊符号',
            tag: '三段码',
          },
        ],
      },
      {
        title: '操作',
        dataIndex: 'id',
        align: 'center',
        width: 230,
        render: (val, record) => {
          const { brand } = record;
          const shouExpandButton = this.expandBrand.includes(brand);
          return (
            <div style={{ textAlign: 'left', marginLeft: 30 }}>
              <Popconfirm title="确定删除该配置？" onConfirm={() => this.deleteList(record)}>
                <Button type="danger" icon="delete">
                  删除
                </Button>
              </Popconfirm>
              {shouExpandButton && (
                <Button
                  onClick={this.onExpandButtonClick.bind(this, record)}
                  style={{ marginLeft: 10 }}
                  type="primary"
                >
                  {this.props.expandedRowKeys.includes(brand) ? '收起' : '展开'}
                </Button>
              )}
            </div>
          );
        },
      },
    ];

    const initBrand = [
      { brand: 'sto', name: '申通快递' },
      { brand: 'yd', name: '韵达快递' },
      { brand: 'zt', name: '中通快递' },
      { brand: 'yt', name: '圆通速递' },
      { brand: 'jt', name: '极兔速递' },
      { brand: 'ems', name: '邮政速递' },
    ];

    this.state = {
      visible: false,
      branchesList: [],
      dataList: [],
      brand: initBrand,
      verificationVisible: false,
      sto_gun_account: '', // 申通输入的工号
      errorFieldsArr: [
        'gun_account',
        'branch_code',
        'third_code',
        'gun_pwd',
        'gun_account_v2',
        'gun_pwd_v2',
      ],
      errMsgMapToBrand: {
        yd: {
          gun_account_v2: '请输入正确的韵镖侠手机号',
          gun_pwd_v2: '请输入韵镖侠密码',
        },
        ht: {
          gun_account_v2: '请输入正确的如来神掌手机号',
          gun_pwd_v2: '请输入正确的如来神掌密码',
        },
        yt: {
          gun_account_v2: '请输入正确的行者手机号',
        },
        ems: {
          gun_account_v2: '请输入正确的邮政设备编码',
        },
      },
    };
  }

  // 检查申通输入的工号是否存在于所选网点内
  async onStoAccountDefocus(gun_account, branch_code) {
    const {
      dispatch,
      record: { courier_phone, courier_no },
    } = this.props;
    this.setState({
      sto_gun_account: gun_account,
    });
    return dispatch({
      type: 'allocation/checkStoGunAccount',
      payload: {
        gun_account,
        branch_code: branch_code.split('-')[0],
        phone: courier_phone,
        kc_code: courier_no,
      },
    }).then(res => {
      const { code } = res;
      if (code != 0) {
        this.triggleOpen(true);
        return code == 1013;
      }
      return true;
    });
  }

  onExpandButtonClick(record, e) {
    e.persist();
    const { expandedRowKeys, dispatch } = this.props;
    const { brand } = record;
    const rowKey = Array.from(new Set(expandedRowKeys));
    const index = rowKey.indexOf(brand);

    if (index >= 0) {
      rowKey.splice(index, 1);
    } else {
      rowKey.push(brand);
    }
    dispatch({
      type: 'operator/updateState',
      payload: {
        expandedRowKeys: Array.from(new Set(rowKey)),
      },
    });
  }

  // 弹窗关闭
  cancelVisible = () => {
    this.setState({
      visible: false,
      dataList: [],
    });
  };

  // 弹窗确认点击
  okVisible = () => {
    const { dispatch, record, selectedSite, listPagination = {} } = this.props;
    const { courier_no, courier_phone } = record;
    const { dataList, brand, errorFieldsArr, errMsgMapToBrand } = this.state;
    const { current: page = 1, pageSize: size = 10 } = listPagination;
    const list = [];
    let flag = false;
    let branchList;
    let brandName;
    if (dataList.length == 0) {
      this.setState({
        visible: false,
      });
      return;
    }
    for (let i = 0; i < dataList.length; i += 1) {
      const { errorFields } = dataList[i];

      for (let b = 0; b < brand.length; b += 1) {
        const bn = brand[b];
        if (dataList[i].brand == bn.brand) {
          brandName = bn.name;
        }
      }

      for (let j = 0; j < errorFieldsArr.length; j += 1) {
        const key = errorFieldsArr[j];
        if (errorFields.indexOf(key) >= 0) {
          flag = false;
          switch (key) {
            case 'branch_code':
              message.error(`请选择${brandName}对应网点信息`);
              return;
            case 'gun_pwd':
              message.error(`请完善${brandName}对应的巴枪密码`);
              return;
            case 'third_code':
              message.error(`请完善${brandName}对应的三段码`);
              return;
            case 'gun_account':
              message.error(`请完善${brandName}对应巴枪账号`);
              return;
            case 'gun_account_v2':
              message.error(errMsgMapToBrand[dataList[i].brand].gun_account_v2);
              return;
            case 'gun_pwd_v2':
              message.error(errMsgMapToBrand[dataList[i].brand].gun_pwd_v2);
              return;
            default:
              break;
          }
        } else {
          flag = true;
        }
      }

      if (!dataList[i].branch_code || dataList[i].branch_code == '') {
        flag = false;
        message.error(`请选择${brandName}对应网点信息`);
        return;
      }
      if (!dataList[i].gun_account || dataList[i].gun_account == '') {
        flag = false;
        message.error(`请完善${brandName}对应巴枪账号`);
        return;
      }
      flag = true;

      if (dataList[i].branch_code != '') {
        branchList = dataList[i].branch_code.split('-');
      } else {
        branchList = [];
      }
      const costList = {
        brand: dataList[i].brand || '',
        gun_account: dataList[i].gun_account || '',
        gun_pwd: dataList[i].gun_pwd || '',
        third_code: dataList[i].third_code || '',
        branch_code: branchList[0] || '',
        kc_code: courier_no,
        gun_account_v2: dataList[i].gun_account_v2,
        gun_pwd_v2: dataList[i].gun_pwd_v2,
      };
      list.push(costList);
    }
    if (flag) {
      const { is_gp_area, site_id } = selectedSite || {};
      dispatch({
        type: 'configuration/userConfig',
        payload: {
          courier_phone,
          list,
          area_id: is_gp_area == 2 ? site_id : undefined,
        },
        then: code => {
          if (code == 0) {
            this.setState({
              visible: false,
              dataList: [],
            });
            dispatch({
              type: 'operator/getOperatorList',
              payload: {
                site_id,
                page,
                size,
              },
            });
          }
        },
      });
    }
  };

  // 下拉改变
  selectChange = value => {
    const { dispatch, user_info = {}, selectedSite } = this.props;
    const { user_type, branchId } = user_info;
    const isYz = user_type == 1;
    const { is_gp_area, site_id } = selectedSite || {};
    dispatch({
      type: 'configuration/getBranchInfo',
      payload: {
        brand: value,
        branch_id: !isYz ? branchId : undefined,
        area_id: is_gp_area == 2 ? site_id : undefined,
      },
      then: response => {
        const { code, data } = response;
        if (code == 0 && data) {
          if (data.length == 0) {
            this.setState({
              branchesList: data,
            });
          } else if (data[value]) {
            this.setState({
              branchesList: uniq(isLegalData(data[value])),
            });
          } else {
            this.setState({
              branchesList: [],
            });
          }
        }
      },
    });
  };

  // 保存巴枪配置修改的数据
  dataSourceChange = (dataSource, action, type) => {
    const { dataList } = this.state;
    const newDataList = cloneDeep(dataList);
    const costList = {
      brand: action.brand || '',
      cm_name: action.cm_name || '',
      cm_phone: action.cm_phone || '',
      gun_account: action.gun_account || '',
      gun_pwd: action.gun_pwd || '',
      branch_code: action.branch_code || '',
      third_code: action.third_code || '',
      id: action.id,
      passed: action.passed,
      errorFields: action.errorFields,
      gun_account_v2: action.gun_account_v2,
      gun_pwd_v2: action.gun_pwd_v2,
    };
    if (type == 'branch_code' && action.brand == 'sto') {
      // 申通切换网点时，清空巴枪工号
      dataSource.filter(val => val.brand == 'sto')[0].gun_account = '';
      newDataList.length != 0 &&
        (newDataList.filter(val => val.brand == 'sto')[0].gun_account = '');
      costList.gun_account = '';
    }

    if (type == 'gun_account' && action.brand == 'sto') {
      const { gun_account, branch_code, passed } = action;
      passed &&
        gun_account &&
        branch_code &&
        this.onStoAccountDefocus(gun_account, branch_code).then(_isPass => {
          if (!_isPass) {
            // 检查输入的工号是否在选择的申通网点内，不存在则清空
            dataSource.filter(val => val.brand == 'sto')[0].gun_account = '';
            newDataList.filter(val => val.brand == 'sto')[0].gun_account = '';
            costList.gun_account = '';
          }
        });
    }
    if (costList) {
      if (newDataList.length == 0) {
        costList.branch_code == '请选择网点' ||
        (costList.branch_code == '' &&
          costList.gun_account == '' &&
          costList.gun_pwd == '' &&
          costList.gun_account_v2 == '' &&
          costList.phone_pwe == '')
          ? ''
          : newDataList.push(costList);

        this.setState({
          dataList: newDataList,
        });
      } else {
        for (let i = 0; i < newDataList.length; i += 1) {
          if (costList.id === newDataList[i].id) {
            newDataList.splice(i, 1);
          }
        }
        newDataList.push(costList);
        if (
          costList.branch_code == '请选择网点' ||
          (costList.branch_code == '' && costList.gun_account == '' && costList.gun_pwd == '')
        ) {
          for (let i = 0; i < newDataList.length; i += 1) {
            if (costList.id === newDataList[i].id) {
              newDataList.splice(i, 1);
            }
          }
        }
        this.setState({
          dataList: newDataList,
        });
      }
    }
    if (type == 'del') {
      for (let j = 0; j < newDataList.length; j += 1) {
        if (costList.id === newDataList[j].id) {
          newDataList.splice(j, 1);
        }
      }
      this.setState({
        dataList: newDataList,
      });
    }
    this.setState({
      dataSource: [...dataSource],
    });
  };

  // 弹窗拉取信息
  configurationVisible = () => {
    const { dispatch, record } = this.props;
    const { courier_no } = record;
    this.setState({
      visible: true,
    });
    dispatch({
      type: 'configuration/getConInfo',
      payload: {
        kc_code: courier_no,
      },
      then: () => {
        const { configuration } = this.props;
        const { conInfoList } = configuration;
        this.setState({
          dataSource: conInfoList,
        });
      },
    });
  };

  // 清除数据
  deleteList = val => {
    const { dispatch, selectedSite } = this.props;
    const { dataSource } = this.state;
    if (val.kc_code) {
      dispatch({
        type: 'configuration/removeInfo',
        payload: {
          kc_code: val.kc_code,
          brand: val.brand,
          branch_code: val.branch_code.split('-')[0],
        },
        then: code => {
          if (code == 0) {
            dataSource.forEach(item => {
              if (item.id == val.id) {
                item.branch_code = undefined;
                item.branch_name = '';
                item.cm_name = '';
                item.cm_phone = '';
                item.gun_account = '';
                item.third_code = '';
                item.gun_pwd = '';
                item.gun_account_v2 = '';
                item.gun_pwd_v2 = '';
              }
            });
            dispatch({
              type: 'operator/getOperatorList',
              payload: {
                site_id: selectedSite.site_id,
              },
            });
            this.dataSourceChange(dataSource, val, 'del');
          }
        },
      });
    } else {
      dataSource.forEach(item => {
        if (item.id == val.id) {
          item.branch_code = undefined;
          item.branch_name = '';
          item.cm_name = '';
          item.cm_phone = '';
          item.gun_account = '';
          item.gun_pwd = '';
          item.third_code = '';
          item.kc_code = '';
          item.gun_account_v2 = '';
          item.gun_pwd_v2 = '';
        }
      });
      this.dataSourceChange(dataSource, val, 'del');
    }
  };

  onQuestionClick = () => {
    Modal.info({
      title: '巴枪账号说明',
      okText: '知道了',
      maskClosable: true,
      width: 750,
      content: (
        <div>
          <p>
            1、申通快递巴枪账号无需维护，如果对应的业务员手机号在梧桐系统中维护过工号，此处会自动显示
          </p>
          <p>2、韵达快递的巴枪账号是业务员编码。示例：1221</p>
          <p>3、圆通速递的巴枪账号是业务员完整的巴枪工号。示例：01881234</p>
          <p>4、中通快递的巴枪账号是业务员完整的巴枪工号。示例：37123.123</p>
          <p>5、极兔速递的巴枪账号是业务员完整的巴枪工号。示例：00049123</p>
        </div>
      ),
    });
  };

  /**
   * @param {boolean} open 开启关闭验证短信弹窗
   * @param {boolean} hasTextPass 短信校验是否通过
   */
  triggleOpen(open, hasTextPass) {
    this.setState({
      verificationVisible: open,
    });
    // 当短信未校验通过，或者用户点击取消校验时，清空巴枪账号
    if (!hasTextPass && !open) {
      this.setState(prevState => {
        const oldState = cloneDeep(prevState);
        oldState.dataList.length > 0 &&
          (oldState.dataList.filter(val => val.brand == 'sto')[0].gun_account = '');
        oldState.dataSource.length > 0 &&
          (oldState.dataSource.filter(val => val.brand == 'sto')[0].gun_account = '');
        return {
          dataList: oldState.dataList,
          dataSource: oldState.dataSource,
        };
      });
    }
  }

  render() {
    const {
      configuration,
      dispatch,
      stoAccountInfo,
      expandedRowKeys,
      hasAuthToChangeHtPwd,
      user_info,
    } = this.props;
    const { conInfoList } = configuration;
    const { dataSource, branchesList, visible, verificationVisible, sto_gun_account } = this.state;
    const selectDataSource = dataSource || conInfoList;

    const { realAccount } = user_info;
    // 假账号
    const fakeAccount = realAccount == 2;
    return (
      <Fragment>
        <Button
          icon="form"
          ghost
          type="primary"
          onClick={() => this.configurationVisible()}
          style={{ marginLeft: 8 }}
          size="small"
          // disabled={disabled}  // 暂时屏蔽
        >
          巴枪配置
        </Button>
        <Modal
          title="巴枪配置"
          visible={visible}
          width={1200}
          onOk={() => this.okVisible()}
          onCancel={() => this.cancelVisible()}
          destroyOnClose
          maskClosable={false}
        >
          <EdiTable
            fakeAccount={fakeAccount}
            columns={this.columnsTable}
            dataSourceChange={this.dataSourceChange}
            dataSourceList={selectDataSource}
            dispatch={dispatch}
            dropdownChange={this.selectChange}
            branchesList={branchesList}
            deleteList={this.deleteList}
            expandedRowKeys={expandedRowKeys}
            hasAuthToChangeHtPwd={hasAuthToChangeHtPwd}
          />
        </Modal>
        <PhoneVerificationCode
          title="添加申通工号验证"
          visible={verificationVisible}
          triggleOpen={this.triggleOpen.bind(this)}
          account={sto_gun_account}
          phone={stoAccountInfo.phone}
          message={stoAccountInfo.message}
        />
      </Fragment>
    );
  }
}

export default Configuration;
